//
//  AccountViewModel.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/11/2.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "AccountViewModel.h"
#import "SVProgressHUD/SVProgressHUD.h"
#import "AFNetworking.h"
#import "UserAccount.h"
#import "WelcomeViewController.h"

static AccountViewModel *accountviewmodel = nil;

@implementation AccountViewModel

//可靠的init方法

- (instancetype)init {
    //
    //    NSString *userInfomanagerCenter = (NSString *)accountviewmodel;
    //
    //    if ([userInfomanagerCenter isKindOfClass:[NSString class]] && [userInfomanagerCenter isEqualToString:@"AccountViewModel"]) {
    //
    if (self = [super init]) {
#pragma mark  问题找到了,此处的加载数据,加载出来之后,完全没有肤质给self.userAccount,使用单例设计模式给予了解决
        UserAccount *account = [UserAccount loadUserAccount];
        //        Optional("2.00n7IerCd4eGIB244a205d7djNvOxC")
        self.userAccount = account;
        
    }
    return self;
}


//单例设计模式的建立,
//重点一 :要了解单例设计模式的作用
// 二:会自己设计单例模式;明白其中流程和步骤,http://www.jianshu.com/p/f61538295d50

+(instancetype)sharedAccountModel;{
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        accountviewmodel = [[AccountViewModel alloc]init];
    });
    return accountviewmodel;
}

- (NSString *)userName{
    return self.userAccount.name;
}
- (NSURL *)headImageURL{
    NSURL *url = [NSURL URLWithString:[AccountViewModel sharedAccountModel].userAccount.avatar_large];
    _headImageURL = url;
    return _headImageURL;
}

-(BOOL)userLogin{
    //一直报错,错误信息为-[UserAccount access_token]: message sent to deallocated instance,原来是__userAccount已经被释放了,空指针访问他自己的access_token属性导致报错的,最后将AccountViewModel类 的_userAccount 属性改为strong才解决了问题
    return _userAccount.access_token != nil;
}


- (NSString *)access_token{
    return _userAccount.access_token;
}


- (BOOL)loadAccessToken:(NSString *)code isSuccess:(success)success{
    
    NSString *urlString = @"oauth2/access_token";
    NSDictionary *parameter = @{@"client_id":client_id,@"client_secret": client_secret,@"grant_type":@"authorization_code",@"code":code,@"redirect_uri":redirect_uri};
    //    AFHTTPSessionManager *AFN = [AFHTTPSessionManager manager];
    //    AFN.responseSerializer.acceptableContentTypes 不支持@"text/plain",此时要头文件"AFURLResponseSerialization.m"的如下地方添加text/plain就行了,即  self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain",@"text/json", @"text/javascript", nil];
    
    [[HTTPClient sharedClient] requestJSONDict:POST urlstring:urlString parameters:parameter finished:^(NSDictionary *dict, NSError *error) {
        if (error != nil) {
            success(false);
            return ;
        }
        UserAccount *useraccount = [[UserAccount alloc]initWithDictionary:dict];
        if (useraccount) {
            NSLog(@"%@",useraccount);
            [self loadUserInfoAccess:useraccount isSuccess:success];
        }
    }];
    return true;
}

- (void)loadUserInfoAccess:(UserAccount *)useraccount isSuccess:(success)success{
//    因为单例中对BaseURL已经进行了设置
    NSString *urlStr = @"2/users/show.json";
    NSDictionary *parameter = @{@"access_token":useraccount.access_token,@"uid":useraccount.uid};
    [[HTTPClient sharedClient] requestJSONDict:GET urlstring:urlStr parameters:parameter finished:^(NSDictionary *dict, NSError *error) {
        if (error != nil) {
            success(false);
            return ;
        }
        NSString *name = dict[@"name"];
        NSString *avatar_large = dict[@"avatar_large"];
        useraccount.name = name;
        useraccount.avatar_large = avatar_large;
        
        NSLog(@"%@,%@,%@",name,avatar_large,useraccount.access_token);
        //        UserAccount *useraccount = [[UserAccount alloc]initWithDictionary:responseObject];
        //        这一步只是把useraccount的值储存到了沙盒中,本模型并没有拿到值
        [useraccount saveAccount];
        //        需要给单例对象的模型赋值,此处的self代表的就是单例对象,这是根据看是谁在最开始调用的这个方法,和下面注释的效果是一样的
        self.userAccount = useraccount;
        //        [AccountViewModel sharedAccountModel].userAccount = useraccount;
        NSLog(@"%@",useraccount);
        success(true);
        
    }];
    
}

@end
